<script lang="ts" setup>
import { nextTick, ref } from 'vue'
import { useUserStore } from '@/store'
import type { MsgItem } from '@/types/room'
import { io, type Socket } from '@hyoga/uni-socket.io'
import RoomStatus from './components/room-status.vue'
import patientInfo from './patient-info/patient-info.vue'
import { getPatientConsultOrderDetailAPI } from '@/api/consult'
import { OrderStatus, type GetPatientConsultOrderDetailData } from '@/types/consult'
import NotifyInfo from '@/subpkg_consult/pages/room/notify-Info/notify-Info.vue'
import MessageInfo from '@/subpkg_consult/pages/room/message-info/message-info.vue'
import PrescriptionInfo from '@/subpkg_consult/pages/room/prescription-info/prescription-info.vue'
import RateInfo from '@/subpkg_consult/pages/room/rate-info/rate-info.vue'
import { UploadImageAPI } from '@/api/common'

const props = defineProps<{
  orderId: string // 订单id
  docId: string // 医生id
  // 是否已评价过
  hasEvaluate: boolean
  // 评价的内容
  evaluateDoc: {
    content: string
    score: number
  }
}>()

const store = useUserStore()
const socket: Socket = io('https://consult-api.itheima.net', {
  auth: { token: `Bearer ${store.token}` }, // 添加token
  query: { orderId: props.orderId }, // 添加订单id
  transports: ['websocket', 'polling'], // 添加传输方式
  timeout: 5000, // 添加超时时间
})

socket.on('connect', () => {
  // 建立连接成功
  console.log('连接建立成功')
})

socket.on('error', (event) => {
  // 错误异常消息
  console.log('出现错误', event)
})

socket.on('disconnect', () => {
  // 已经断开连接
  console.log('断开连接')
})

// 获取订单详情
const orderDetail = ref<GetPatientConsultOrderDetailData>()
const getOrderDetail = async () => {
  const res = await getPatientConsultOrderDetailAPI(props.orderId)
  console.log('订单详情', res)
  orderDetail.value = res.data
}
getOrderDetail()

// 监听订单状态变化，statusChange 为后端定义的事件名称
socket.on('statusChange', (data) => {
  // console.log('订单状态变化', data)
  // 重新获取订单详情，包含订单状态，倒计时秒数
  getOrderDetail()
})

const msgList = ref<MsgItem[]>([])

// 2. 获定义的取历史消息，后端事件名称为 chatMsgList
socket.on('chatMsgList', (res) => {
  console.log('历史消息', res)
  // 业务状态吗
  if (res.code !== 10000) return
  // 保存消息列表
  res.data?.forEach((item: any) => {
    // 如果是消息列表, 则将消息列表中的消息添加到msgList中
    if (item.items) {
      msgList.value.push(
        {
          msgType: 31,
          createTime: item.createTime,
          msg: {
            content: item.createTime,
          },
        },
        ...item.items
      )
    }
  })
})

// 1. 监听订单状态变化，后端定义的事件名称为 statusChange
socket.on('statusChange', () => {
  // 重新获取订单详情，包含订单状态，倒计时秒数
  getOrderDetail()
})

const scrollIntoView = ref('')
// 3. 接收回复消息，后端定义的事件名称为 receiveChatMsg
socket.on('receiveChatMsg', async (res: MsgItem) => {
  console.log('接收回复消息', res)
  // 追加到消息数组中
  msgList.value.push(res)
  // 通知后端，前端消息已读
  socket.emit('updateMsgStatus', res.id)
  // 通过nextTick 获取最新的消息
  await nextTick()
  // 接收消息后,滚动到最新消息
  scrollIntoView.value = `id-${res.id}`
})

// 发送文字消息
const textMessage = ref('')

// 发送文字消息
const sendTextConfirm = () => {
  // console.log('发送文字消息', textMessage.value)
  // 发送消息
  socket.emit('sendChatMsg', {
    // 当前登录用户的Id
    from: store.userInfo?.id,
    // 医生Id
    to: orderDetail.value?.docInfo?.id,
    msgType: 1, // 消息类型，1为文字消息
    msg: {
      content: textMessage.value,
    },
  })
  // 清空输入框
  textMessage.value = ''
}

// 发送图片消息
const sendImageConfirm = async () => {
  if (orderDetail.value?.status !== OrderStatus.ZiXunZhong) {
    return uni.showToast({
      title: '当前状态不能发送图片消息',
      icon: 'none',
    })
  }
  const { tempFilePaths } = await uni.chooseImage({
    count: 1, // 最多可以选择的图片张数
    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
  })
  // console.log('选择图片', tempFilePaths)

  // 上传图片
  const uploadRes = await UploadImageAPI(tempFilePaths[0])
  // console.log('上传图片', uploadRes)
  // 发送图片消息
  socket.emit('sendChatMsg', {
    from: store.userInfo?.id,
    to: orderDetail.value.docInfo?.id,
    msgType: 2, // 消息类型，2为图片消息
    msg: {
      content: uploadRes.data,
    },
  })
}
</script>

<template>
  <view class="room-page">
    <RoomStatus
      v-if="orderDetail"
      :status="orderDetail?.status"
      :status-value="orderDetail?.statusValue"
      :countdown="orderDetail?.countdown"
    />
    <scroll-view
      refresher-enabled
      refresher-background="#f2f2f2"
      scroll-y
      style="flex: 1; overflow: hidden"
      :scroll-into-view="scrollIntoView"
    >
      <view class="message-container">
        <!-- 此处将来填充更多代码... -->
        <view v-for="item in msgList" :key="item.id" :id="`id-${item.id}`">
          <patientInfo v-if="item.msgType === 21" :info="item.msg?.consultRecord!" />
          <!-- 通知信息，普通通知（31）和温馨提示（32） -->
          <NotifyInfo v-if="item.msgType && item.msgType >= 31" :type="item.msgType">
            {{ item.msg?.content }}
          </NotifyInfo>
          <!-- 气泡消息 -->
          <MessageInfo v-if="item.msgType === 1 || item.msgType === 4" :message="item" />
          <!-- 电子处方 -->
          <PrescriptionInfo v-if="item.msg?.prescription" :info="item.msg?.prescription" />
          <!-- 医生评价 -->
        </view>
      </view>
    </scroll-view>

    <!-- 发送消息 -->
    <view class="message-bar">
      <template v-if="true">
        <uni-easyinput
          :disabled="orderDetail?.status !== 3"
          v-model="textMessage"
          @confirm="sendTextConfirm"
          :clearable="false"
          :input-border="false"
          placeholder-style="font-size: 32rpx; color: #c3c3c5;"
          placeholder="问医生"
        />
        <view class="image-button" @click="sendImageConfirm">
          <uni-icons size="40" color="#979797" type="image"></uni-icons>
        </view>
      </template>
      <button v-else class="uni-button">咨询其它医生</button>
    </view>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
